/**
 * 
 */
package stc.skymobi.content.store;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import stc.skymobi.content.ContentStore;

import com.danga.MemCached.MemCachedClient;

/**
 * @author hp
 *
 */
public class TokyotyrantContentStore implements ContentStore {

    private static final Logger logger = 
    	LoggerFactory.getLogger(TokyotyrantContentStore.class);
    
	private	MemCachedClient mc;
	
	public TokyotyrantContentStore(String poolname) {
		mc = new MemCachedClient(poolname);
		//	bcs of ttserver not support compress feature.
		mc.setCompressEnable(false);
	}
	
	/* (non-Javadoc)
	 * @see com.skymobi.content.ContentStore#contains(java.lang.String)
	 */
	public boolean contains(String key) {
		return	mc.keyExists(key);
	}

	/* (non-Javadoc)
	 * @see com.skymobi.content.ContentStore#fetch(java.lang.String)
	 */
	public byte[] fetch(String key) {
		return (byte[])mc.get(key);
	}

	/* (non-Javadoc)
	 * @see com.skymobi.content.ContentStore#remove(java.lang.String)
	 */
	public boolean remove(String key) {
		return false;
	}

	/* (non-Javadoc)
	 * @see com.skymobi.content.ContentStore#store(byte[])
	 */
	public String store(byte[] content) {
		String key = ContentStoreUtils.content2key(content);
		boolean ret = mc.add(key, content);
		if ( ret ) {
			return	key;
		}
		else {
			byte[] old = (byte[])mc.get(key);
			if ( Arrays.equals(content, old) ) {
				logger.info("content for key [" + key + "] already exist. just ingore");
				return key;
			}
			else {
				logger.error("key [" + key + "] already exist. but content mismatch, maybe internal error?");
			}
			return	null;
		}
	}

	public List<String> getKeys() {
		return new ArrayList<String>();
	}

}
